
Ext.define('ZYY.controller.Desktop' ,{
    extend: 'Ext.app.Controller',
        mixins: {
        manager: 'Ext.ux.webdesktop.Manager'
    },
    views: [
     'ZYY.view.webdesktop.Viewport'
    ],

   stores:[
     'ZYY.store.webdesktop.Shortcuts'
   ],
    requires: [
         'ZYY.view.webdesktop.Taskbar',
         'Ext.ux.webdesktop.ModuleCollection',
         'Ext.ux.webdesktop.Module'
         
    ],
	refs: [
        { ref: 'taskBar',       selector: 'webdesktop_taskbar'},
        {ref:'webdesktop',      selector:'webdesktop_desktop'},
        { ref: 'startMenu',     selector: 'webdesktop_startmenu'},
        { ref: 'toolBar',       selector: 'webdesktop_startmenu toolbar[cls=ux-start-menu-toolbar]'},
        { ref: 'quickStart',    selector: 'webdesktop_taskbar #ux-desktop-quickstart'},
        { ref: 'windowBar',     selector: 'webdesktop_taskbar #ux-desktop-windowbar'},
        { ref: 'systemTray',    selector: 'webdesktop_taskbar #ux-desktop-systemtray'},
        { ref: 'windowBarContextMenu', selector: '#taskbar-contextmenu'},
        { ref: 'viewPort',      selector: 'webdesktop_viewport'},
        { ref: 'wallpaper',     selector: 'webdesktop_wallpaper'},
        {ref:'taskbar',selector:'webdesktop_taskbar'},
       { ref: 'shortcutsView', selector: 'webdesktop_desktop dataview[itemId=ux-shortcut]'}
    ],
        config: {
        /**
         * 背景桌面url
         * Provided after the this::bindUser() is called
         * @cfg {String} wpUrl
         */
        wpUrl               : '',
        /**
         * URL to load the Themes
         * Provided after the this::bindUser() is called
         * @cfg {String} themesUrl
         */
        themesUrl           : '',
        /**
         * URL to load the preview images of themes
         * Provided after the this::bindUser() is called
         * @cfg {String} themePreviewUrl
         */
        themePreviewUrl     : '',
        /**
         * The complete user config from the backend after the user logged in
         * Provided after the this::bindUser() is called
         * @cfg {Object} userConfig
         * @todo check if it is better in the new style, to use a model/store here
         */
        userConfig          : {},
        /**
         * currently selected Theme
         * @cfg {String} theme (default to 'ext-all.css' / sencha default blue)
         */
        theme               : 'ext-all.css',
        /**
         * CSS class to append to the active window
         * @cfg {String} activeWindowCls
         */
        activeWindowCls     : 'ux-desktop-active-win',
        /**
         * CSS class to append to inactive window(s)
         * @cfg {String} inactiveWindowCls
         */
        inactiveWindowCls   : 'ux-desktop-inactive-win',

        taskbarWindowMenu   : {
            defaultAlign    : 'br-tr',
            itemId          : 'taskbar-contextmenu',
            items           : [
                { text: '还原',  actionType: 'restore'},
                { text: '最小化', actionType: 'minimize'},
                { text: '最大化', actionType: 'maximize'},
                '-',
                { text: '关闭',    actionType: 'close'}
            ]
        },
        /**
         * Config for the quickstart buttons
         * placeholders will be overwritten in self::onBeforeAddQuickstart()
         *
         * @cfg {Object} quickStartButton
         * @todo rename to quickStartButtonTemplate (and all usages)
         */
        quickStartButton: {
            text: null,
            overflowText: 'placeholder',
            tooltip: {
                align: 'bl-tl'
            }
        },
        /*桌面右键*/
        desktopMenuBar:{
            defaultAlign    : 'br-tr',
            items           : [
                { text: '平铺显示',  actionType: 'pp',minWindows: 1},
                { text: '重叠显示', actionType: 'cd',minWindows: 1 }
            ]
        
        }
    },
    shortcuts: null,
    launchers:null,
    init: function() {
//    	var str="{aaa:11,bbb:222,ccc:333}";
//    	alert(Ext.JSON.decode(str));
          var me = this;
        me.initConfig(this.config);
        me.mixins.manager.constructor.call(this, {desktop: me});
         me.shortcuts  = Ext.data.StoreManager.get('ZYY.store.webdesktop.Shortcuts');  
    	  me.windowMenu = Ext.create('Ext.menu.Menu', me.getTaskbarWindowMenu());
    	  //左面右键
    	   me.deskMenu = Ext.create('Ext.menu.Menu', me.getDesktopMenuBar());
          me.control({
            'webdesktop_viewport' : {
				    afterlayout : me.initWindowBarMenu,
				    afterrender:me.viewportshow
					},
					//桌面 右键 方法 
					'webdesktop_desktop' : {
					afterrender : me.initDesktopMenu
					
					},
					'#taskbar-contextmenu' : {
						  beforeshow: me.onWindowMenuBeforeShow,
						hide : me.onWindowMenuHide
					},
					'#taskbar-contextmenu > menuitem[actionType=restore]' : {
						click : me.onWindowMenuRestore
					},
					'#taskbar-contextmenu > menuitem[actionType=minimize]' : {
						click : me.onWindowMenuMinimize
					},
					'#taskbar-contextmenu > menuitem[actionType=maximize]' : {
						click : me.onWindowMenuMaximize
					},
					'#taskbar-contextmenu > menuitem[actionType=close]' : {
						click : me.onWindowMenuClose
					},
					'webdesktop_taskbar #ux-desktop-quickstart' : {
						beforeadd : me.onBeforeAddQuickstart//,
						// afterrender:me.quickStartshow
					},
					'webdesktop_taskbar #ux-desktop-quickstart > button' : {
						click : me.onClickModuleHandler
					},
					
					'webdesktop_startmenu menu menuitem' : {
						click : me.onClickModuleHandler
					},
					'webdesktop_startmenu toolbar[dock=right] button' : {
						click : me.onClickModuleHandler
					},
					'webdesktop_desktop dataview[itemId=ux-shortcut]' : {
						itemclick : me.onClickShortcut,
					    viewready:me.initShortcut


					},
					'webdesktop_startmenu' : {
						afterrender : me.onStartMenuAfterRender,
						show:me.StartMenuItems
					}

    })
    	//this.bindUser
   this.bindUser({
        "themesUrl":"",
        "id":1,
        "launchers":{
            "shortcut":["grid-win","systemstatus","summary"
            ],
            "quickstart":["grid-win","grid-win1"],
            "autorun":["grid-win"]
        },
        "modules":[
            {
                "launcher":{
                    "text":"项目综合管理",
                    "moduleId":"grid-win",
                    "iconCls":"icon-grid",
                    "tooltip":"项目综合管理"
                },
                "moduleId":"grid-win",
                "name":"项目综合管理",
                "controller":"grid.SytemDesk",
                "desk":"show",
                "iconCls":"grid-shortcut",
                "pos":"left"
            },
            {
                "launcher":{
                    "text":"文件管理",
                    "moduleId":"grid-win1",
                    "iconCls":"icon-grid",
                    "tooltip":"文件管理"
                },
                "moduleId":"grid-win1",
                "name":"文件管理",
                "controller":"grid.Grid",
                "desk":"hiden",
                "iconCls":"grid-shortcut",
                "pos":"right"
            },
              {
              "launcher":{
              "text":"统计",
              "moduleId":"systemstatus",
              "iconCls":"icon-grid",
              "tooltip":"系统分析"
              },
              "moduleId":"systemstatus",
              "name":"统计",
              "controller":"char.Char",
              "desk":"hidden",
              "iconCls":"cpu-shortcut",
              "pos":"right"
            },             {
              "launcher":{
              "text":"汇总",
              "moduleId":"systemstatus",
              "iconCls":"icon-grid",
              "tooltip":"系统分析"
              },
              "moduleId":"summary",
              "name":"汇总",
              "controller":"summary.MyController",
              "desk":"hidden",
              "iconCls":"cpu-shortcut",
              "pos":"right"
            }
            
        ],
        "wpUrl":"wallpapers/Blue-Sencha.jpg"
    });
    Ext.create("ZYY.view.webdesktop.Viewport1");
    },
    viewportshow:function(){
    	var me =this;
         Ext.each(launchers.autorun, function(item) {
            var module = me.getModules().get(item),
                cn = me.application.getController(module.controller);
                if(!cn.isInit) {
                    cn.init(me.application, me);
                }
                cn.launch();
        }, me);
    },
     doshorcuts:function(node,check){
     	var me = this;
     	   modules = me.getModules(),
            module = modules.get(node.raw.moduleId),
            store = me.shortcuts,
            record = store.findRecord('moduleId', module.moduleId);
     	if(check){
     		//me.shortcuts.add({moduleId:'grid-win',name:'疯子',iconCls:'grid-shortcut'});
     		store.add(module);
     	}else{
     	me.shortcuts.remove(me.shortcuts.findRecord('moduleId',node.get('moduleId')));
     	}
     	wallpapers='wallpapers/desk.jpg';
     	me.getWallpaper().setWallpaper(wallpapers,true);
     	me.initShortcut();
     },
    getManager: function() {
        return this.manager;
    },
    quickStartshow:function(){
    	var me =this;
            Ext.each(launchers.quickstart, function(item) {
             	
            var module = me.getModules().get(item);
            if(module) {
           var xc =  me.getQuickStart().add(Ext.apply({
              	 moduleId: module.moduleId
            }, module.launcher));
            xc.setHandler(me.onClickModuleHandler,me);
            }
           
        }, me);
    },
     bindUser: function(config) {
        var me = this,  modules   = config.modules || {};
        launchers = config.launchers || {};
        wallpapers  =config.wpUrl;
        me.setUserConfig(config);
        me.getModules().addAll(modules);
        
        


         var fnAddQuick = Ext.bind(function(module) {
           var xc = me.getQuickStart().add(Ext.apply({
                moduleId: module.moduleId
            }, module.launcher));
            xc.setHandler(me.onClickModuleHandler,me);
        }, me); 
//        
              //             autorun
//        Ext.each(launchers.autorun, function(item) {
//            var module = me.getModules().get(item),
//                cn = me.application.getController(module.controller);
//                if(!cn.isInit) {
//                    cn.init(me.application, me);
//                }
//                cn.launch();
//        }, me);
        
                Ext.each(launchers.quickstart, function(item) {
            var module = me.getModules().get(item);
            if(!me.getQuickStart()) {
                // its not rendered yet, give it some time
                Ext.defer(fnAddQuick, 300, me, [module]);
            } else {
                fnAddQuick(module);
            }
        }, me);
        
                Ext.each(launchers.shortcut, function(item) {
            me.shortcuts.add(me.getModules().get(item));
        }, me);

   },
    onClickModuleHandler: function(cmp, event) {
        if(!cmp.moduleId) {
            return false;
        };
        var me     = this,
            module = me.getModules().get(cmp.moduleId),
          
           cn     = me.application.getController(module.controller);
        if(!cn.isInit) {
            cn.init(me.application, me);     
        }
        cn.launch();
        return true;
    },

    onClickShortcut: function(view, record) {
        var me     = this,
         module = me.getModules().get(record.get('moduleId')); 
        return me.onClickModuleHandler(module)
    },
   
    initShortcut : function() {
    	//两个图标上下距离
				var btnHeight = 60;
				//两个图标左右距离
				var btnWidth = 60;
				//填充
				var btnPadding = 30;
				var col = null;
				var row = null;
				//最下面图标的位置 
				var bottom;
				var numberofIterms = 0;
				var bodyHeight = Ext.getBody().getHeight();

				function initColRow() {
					col = {
						index : 1,
						x : btnPadding
					};
					row = {
						index : 1,
						y : btnPadding
					};
				}

				function isOverflow(value, bottom) {
					if ( bodyHeight < bottom) {
						return true;
					}
					return false;
				}

				this.setXY = function(item) {
					 bodyHeight = Ext.getBody().getHeight();
					numberofIterms += 1;
					bottom = row.y + btnHeight;
					overflow = isOverflow(numberofIterms, bottom);
					if (overflow && bottom > (btnHeight + btnPadding)) {
						numberofIterms = 0;
						col = {
							index : col.index++,
							x : col.x + btnWidth + btnPadding
						};
						row = {
							index : 1,
							y : btnPadding
						};
					}
					Ext.fly(item).setXY([col.x, row.y]);
					row.index++;
					row.y = row.y + btnHeight + btnPadding;
				};

				this.handleUpdate = function() {
					initColRow();
					var items = Ext.query(".ux-desktop-shortcut");
					for (var i = 0, len = items.length; i < len; i++) {
						this.setXY(items[i]);
					    
					}
				};
				this.handleUpdate();
				Ext.EventManager.onWindowResize(this.handleUpdate, this, {delay:100});
	           Ext.EventManager.onDocumentReady(this.handleUpdate, this, {delay:5});
			},
			 /**
     * Add element to windowbar
     *
     * @param {Ext.window.Window} win
     * @todo move to Ext.ux.webdesktop.Manager
     * @todo rename to addWindowBarButton
     */
    addTaskButton: function(win) {
        var me = this,
            fn = function(config, win) {
                var cmp = me.getWindowBar().add(config);
                 cmp.toggle(true);
                // add the taskbutton reference to the window here
                win.taskButton = cmp;
                win.animateTarget = cmp.el;
            },
            config = {
                iconCls      : win.iconCls,
                enableToggle : true,
                toggleGroup  : 'all',
                width        : 140,
                text         : Ext.util.Format.ellipsis(win.title, 20),
                win          : win,
                listeners    : {
                    click : me.onWindowBtnClick,
                    scope : me
                }
            };
  
        // if windowbar isnt rendered yet, defer
        if(!me.getWindowBar()) {
            Ext.defer(fn, 500, me, [config, win]);
        } else {
            fn(config, win);
        }
    },
        /**
     * Remove a button from the WindowBar
     *
     * @param {Ext.button.Button} btn
     * @return {Ext.button.Button} found
     * @todo move to Ext.ux.webdesktop.Manager
     * @todo rename to removeWindowBarButton
     */
    removeTaskButton: function(btn) {
        var me = this,
            found;
        me.getWindowBar().items.each(function (item) {
            if (item === btn) {
                found = item;
            }
            return !found;
        });
        if (found) {
            me.getWindowBar().remove(found);
        }
        return found;
    },
        /**
     * Mark a button in the WindowBar as active element
     *
     * @param {Ext.button.Button} btn
     * @todo move to Ext.ux.webdesktop.Manager
     * @todo rename to setActiveWindowBarButton
     */
    setActiveButton: function(btn) {
        if (btn) {
            btn.toggle(true);
        } else {
            if(this.getWindowBar()) {
                this.getWindowBar().items.each(function (item) {
                    if (item.isButton) {
                        item.toggle(false);
                    }
                });
            }
        }
    },
        /**
     * OnClick Element in windowbar
     *
     * @param {Ext.button.Button} btn
     */
    onWindowBtnClick: function (btn) {
        var win = btn.win;
        if (win.minimized || win.hidden) {
            win.show();
        } else if (win.active) {
            win.minimize();
        } else {
            win.toFront();
        }
    },
        /**************************************************************************\
    | EVENT BINDING
    \**************************************************************************/

    /**
     * Bind the ContextMenu to the windowbar
     */
    initWindowBarMenu: function() {
    	
        this.getWindowBar().el.on('contextmenu', this.onWindowBarButtonContextMenu, this);
    },
        /**
     * Show and place the context menu when right clicked
     * on the window bar element
     *
     * @param {Object} event
     */

    onWindowBarButtonContextMenu: function(event) {
        var me  = this,
            t   = event.getTarget(),
            btn = this.getWindowBar().getChildByElement(t) || null;
             me.windowMenu.on('beforeshow', me.onWindowMenuBeforeShow, me);
        if (btn) {
            event.stopEvent();
            me.windowMenu.currentWindow = btn.win;
            me.windowMenu.showBy(t);
        }
    },
    //桌面 右键 
     initDesktopMenu:function(){
       this.getWebdesktop().el.on('contextmenu',this.onDesktopMenu,this);
        
    },
        onBeforeAddQuickstart: function(toolbar, button) {
        	var me =this;
        return Ext.apply(
            button,
            Ext.apply(this.getQuickStartButton(), {
                overflowText: button.text,
                tooltip     : {
                    text : button.text
               
                }
              //  handler:function(me.onClickModuleHandler,me);
            }
        )
        
        );
    },
        /**
     * fires before the context menu on the windowbar is shown
     * set the contents of the contextmenu to the current window options
     *
     * @param {Ext.menu.Menu} menu
     */
    onWindowMenuBeforeShow: function(menu) {
        var items = menu.items.items,
            win   = menu.currentWindow;
        items[0].setDisabled(win.maximized !== true && win.hidden !== true); // Restore
        items[1].setDisabled(win.minimized === true); // Minimize
        items[2].setDisabled(win.maximized === true || win.hidden === true); // Maximize
    },
   //桌面右键 
    onDesktopMenu:function(e){
    	//this.getDesktop().getWebdesktop().center().setHeight(500);
    	var me = this, menu = me.deskMenu;
        e.stopEvent();
         menu.on('beforeshow', me.onDesktopMenuBeforeShow, me);
        menu.showAt(e.getXY());
        menu.doConstrain();
       menu.items.each(function (item){
               if(item.actionType=="pp"){

              item.on('click',me.tileWindows,me);
              }
              if(item.actionType=="cd"){
              item.on('click',me.cascadeWindows,me);
              }

      });
    },
      //右键菜单显示之前的监听方法 
    onDesktopMenuBeforeShow: function (menu) {
        var me = this, count = me.windows.getCount();
        menu.items.each(function (item) {
            var min = item.minWindows || 0;
            //设置右键菜单中的选项是否可以使用 false可以使用

            item.setDisabled(count < min);
      
        });
    },
    /**
     * 关闭工具栏按钮
     */
    onWindowMenuHide: function() {
        this.getWindowBarContextMenu().currentWindow = null;
    },
        /**
     * 还原窗口
     * restores a minized window
     */
    onWindowMenuRestore: function() {
        var me  = this,
            win = me.getWindowBarContextMenu().currentWindow;
        me.onRestoreWindow(win);
    },

    /**
     * fires when clicking "minimize" in the context menu
     * minimize the window
     */
    onWindowMenuMinimize: function() {
        this.getWindowBarContextMenu().currentWindow.minimize();
    },

    /**
     * fires when clicking "close" in the context menu
     * close the window
     */
    onWindowMenuClose: function() {
    	
        this.getWindowBarContextMenu().currentWindow.close();
        
    },
        /**
     * fires when clicking "maximize" in the context menu
     * maximize the window
     */
    onWindowMenuMaximize: function() {
        this.getWindowBarContextMenu().currentWindow.maximize();
    },
    /**
     * fires after the startmenu renders
     * Set the title of the panel
     *
     * @param {Webdesktop.view.webdesktop.StartMenu} panel
     * @todo Need user informations with the load of the page in GLOBAL_USER_PROFILE to set the title here
     */
    onStartMenuAfterRender: function(panel) {
        panel.setTitle('开始菜单'); // FIXME: @todo see methods doc
    },
       //窗口平铺方法
    tileWindows: function() {
    	var me = this
        availWidth = me.getWebdesktop().body.getWidth(true);
        var x = me.xTickSize, y = me.yTickSize, nextY = y;
        me.windows.each(function(win) {
        	alert(win.isVisible() && !win.maximized);
        	alert(win.isVisible());
            if (win.isVisible() && !win.maximized) {
                var w = win.el.getWidth();
     
                // Wrap to next row if we are not at the line start and this Window will
                // go off the end
                if (x > me.xTickSize && x + w > availWidth) {
                    x = me.xTickSize;
                    y = nextY;
                }

                win.setPosition(x, y);
                x += w + me.xTickSize;
                nextY = Math.max(nextY, y + win.el.getHeight() + me.yTickSize);
            }
        });
    },
        //窗口重叠方法
    cascadeWindows: function() {
    	var me =this;
        var x = 0, y = 0,
            zmgr = this.getDesktopZIndexManager();

        zmgr.eachBottomUp(function(win) {
            if (win.isWindow && win.isVisible() && !win.maximized) {
                win.setPosition(x, y);
                x += 20;
                y += 20;
            }
        });
    },
    StartMenuItems:function(){
    	
    	me=this;
    	me.getStartMenu().menu.removeAll();
    	me.getStartMenu().getDockedComponent("ux-start-menu-toolbar").removeAll();
        me.getModules().each(function(module){
        if(module.pos=='left'){
        me.getStartMenu().menu.add(module.launcher);
        me.getStartMenu().menu.add('-');

      }else{
        me.getStartMenu().getDockedComponent("ux-start-menu-toolbar").insert(0, module.launcher)
      	me.getStartMenu().getDockedComponent("ux-start-menu-toolbar").add('->')
      }
     })
    }
    

  });